package com.flash.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flash.properties.BaiDuProperties;
import com.flash.exception.OrderBusinessException;
import com.flash.result.BaiDuLocation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;



@Component
public class BaiDuMapUtils {
    //获取经纬度api
    @Autowired
    private BaiDuProperties baiDuProperties;

    public static final String getGeoPos = "https://api.map.baidu.com/geocoding/v3/?";
    public static final String getDistance = "https://api.map.baidu.com/routematrix/v2/riding?";


    public BaiDuLocation getGetGeoPos(String address) throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        /*拼接url访问*/
        String url = getGeoPos + "address=" + address +
                "&output=json&ak=" + baiDuProperties.getAk() +
                "&callback=showLocation";
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity responseEntity = response.getEntity();
        String s = EntityUtils.toString(responseEntity);
        String jsonResponse = s.replace("showLocation&&showLocation(", "").replace(")", "");
        Map<String, Object> responseMap = JSON.parseObject(jsonResponse, Map.class);
        if (responseMap.get("status").equals(0)) { // 判断请求是否成功
           Map<String ,Object>res = (Map<String, Object>) responseMap.get("result");
           Map<String,Object>location = (Map<String, Object>) res.get("location");
            BaiDuLocation baiDuLocation = new BaiDuLocation();
            baiDuLocation.setLng((BigDecimal) location.get("lng"));
            baiDuLocation.setLat((BigDecimal) location.get("lat"));
            return baiDuLocation;
        } else {
            System.out.println("请求失败，状态码: " + responseMap.get("status"));
            return null;
        }
    }
    public boolean couldDelivery(String desName)throws IOException{
        // 构建参数
        Map<String, String> params = new LinkedHashMap<>();
        params.put("ak", baiDuProperties.getAk());
        BaiDuLocation shop = getGetGeoPos(baiDuProperties.getShopAddress());
        String origins = shop.getLat() + "," + shop.getLng();
        params.put("origins", origins);
        BaiDuLocation des = getGetGeoPos(desName);
        String desL = des.getLat().toString() + "," + des.getLng().toString();
        params.put("destinations", desL);
        params.put("ret_straight_dist", "1");

        // 使用 UriComponentsBuilder 构建 URL
        String url = UriComponentsBuilder.fromHttpUrl(getDistance)
                .queryParam("output", "json")
                .queryParam("origins", params.get("origins"))
                .queryParam("destinations", params.get("destinations"))
                .queryParam("ak", params.get("ak"))
                .queryParam("ret_straight_dist", params.get("ret_straight_dist"))
                .build()
                .toUriString();

        System.out.println("请求 URL: " + url);

        // 发送 HTTP 请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = client.execute(get);
        HttpEntity responseEntity = response.getEntity();
        String responseString = EntityUtils.toString(responseEntity);
        System.out.println("响应结果: " + responseString);
        JSONObject jsonObject = JSON.parseObject(responseString);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

       /* //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
*/
        return true;
    }

}
